package com.liuzhilin.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.liuzhilin.domain.Message;
import com.liuzhilin.service.MessageService;
import com.liuzhilin.util.Response;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.Map;

@WebServlet("/emailSend")
public class EmailSend extends HttpServlet {

    // POST方法，用于接收前端发送的消息
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置响应内容类型为JSON
        Response.setCorsHeaders(response);
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();

        try {
            ObjectMapper mapper = new ObjectMapper();
            Map<String, String> jsonMap = mapper.readValue(request.getReader(), Map.class);

            // 从前端请求体中获取信息
            String sendMessage = jsonMap.get("currentUsername");
            String receiveMessage = jsonMap.get("friendUsername");
            String content= jsonMap.get("message");

            boolean success = MessageService.sendMessage(sendMessage,content,receiveMessage,0);

            // 根据插入结果返回响应
            if (success) {
                response.setStatus(HttpServletResponse.SC_OK);
                out.print("{\"message\": \"消息发送成功\"}");
            } else {
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                out.print("{\"message\": \"消息发送失败\"}");
            }

        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            out.print("{\"message\": \"服务器错误\"}");
        }
    }

    @Override
    public void doOptions(HttpServletRequest request, HttpServletResponse response) {
        // 设置 CORS 头部
        Response.setCorsHeaders(response);
        response.setStatus(HttpServletResponse.SC_OK);
    }
}